package com.zjun.demo.experimentaldemo.album_operate

import android.content.ContentResolver
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import java.io.File

/**
 * 查询相册指定位置的图片是否存在
 */
fun ContentResolver.queryMedia(name: String, relativePath: String): Boolean {
    val projection = arrayOf(
        MediaStore.Images.Media.DISPLAY_NAME,
        MediaStore.Images.Media.RELATIVE_PATH,
        MediaStore.Images.Media.DATA
    )
    val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val selection:String
    val selectionArgs:Array<String>
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        selection = "${MediaStore.Images.Media.DISPLAY_NAME}=? AND ${MediaStore.Images.Media.RELATIVE_PATH}=?"
        selectionArgs = arrayOf(name,Environment.DIRECTORY_PICTURES + File.separator + relativePath + File.separator)
    }else{
        val sdf = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        val sdfdsf =File(sdf, relativePath)
        val file =File(sdfdsf, name)
        selection = "${MediaStore.Images.Media.DISPLAY_NAME}=? AND ${MediaStore.Images.Media.DATA}=?"
        selectionArgs = arrayOf(name,file.absolutePath)
    }
    query(uri, projection, selection, selectionArgs, null)?.use {
        return if(it.moveToNext()){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                val displayNameIndex = it.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)
                val relativePathIndex = it.getColumnIndex(MediaStore.Images.Media.RELATIVE_PATH)
                val displayName = it.getString(displayNameIndex)
                val relativePathDSF = it.getString(relativePathIndex)
                relativePathDSF
            }else{
                val displayNameIndex = it.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)
                val relativePathIndex = it.getColumnIndex(MediaStore.Images.Media.DATA)
                Environment.DIRECTORY_PICTURES + File.separator + relativePath + File.separator
            }
            true
        }else{
            false
        }
    }
    return false
}






